package br.com.serialmanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.serialmanager.model.bean.Mascara;
import br.com.serialmanager.model.bean.Software;
import br.com.serialmanager.model.dao.MascaraDao;
import br.com.serialmanager.model.dao.SoftwareDao;
import br.com.serialmanager.util.Mask;

public class NovoSoftwareActivity extends Activity implements OnItemSelectedListener, OnCheckedChangeListener {
	
	private static final String EXTRA_SOFTWARE_ID = "EXTRA_SOFTWARE_ID";

	private SoftwareDao softwareDao;
	private Date dataValidade;
	private Button btnVencimentoSoftware;
	private SimpleDateFormat formatter;
	private EditText nomeSoftware, numeroDeSerie;
	private Calendar calendar;
	private String idSoftware;
	private Spinner spinnerMascara;
	private ArrayAdapter<String> adapter;
	private MascaraDao mascaraDao;
	private List<String> mascaras;
	private TextWatcher numeroDeSerieMask;
	private CheckBox vencimentoIndefinido;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.novo_software);
		
		this.formatter = new SimpleDateFormat("dd/MM/yyyy");
		this.calendar = Calendar.getInstance();
		this.softwareDao = new SoftwareDao(this);
		this.mascaraDao = new MascaraDao(this);
		
		this.btnVencimentoSoftware = (Button) this.findViewById(R.id.vencimentoSoftware);
		this.nomeSoftware = (EditText) this.findViewById(R.id.nomeDoSoftware);
		this.numeroDeSerie = (EditText) this.findViewById(R.id.numeroDeSerie);
		this.spinnerMascara = (Spinner) this.findViewById(R.id.spinnerMascara);
		this.vencimentoIndefinido = (CheckBox) this.findViewById(R.id.vencimentoIndefinido);
		this.dataValidade = this.calendar.getTime();
		
		this.vencimentoIndefinido.setOnCheckedChangeListener(this);
		this.btnVencimentoSoftware.setText(this.formatter.format(this.calendar.getTime()));
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.mascaras = this.getListaMascaras();
		ArrayAdapter<String> adapterMascaras = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, this.mascaras);
		this.spinnerMascara.setAdapter(adapterMascaras);
		this.spinnerMascara.setOnItemSelectedListener(this);
		
		this.idSoftware = this.getIntent().getStringExtra(EXTRA_SOFTWARE_ID);
		if (this.idSoftware != null) {
			this.carregarSoftware();
		}
	}
	
	private List<String> getListaMascaras() {
		// TODO Auto-generated method stub
		List<Map<String, Object>> itens = this.mascaraDao.listarMascaras();
		List<String> mascaras = new ArrayList<String>();
		if (!itens.isEmpty()) {
			for (Map<String, Object> map : itens) {
				mascaras.add(map.get("masc_formato").toString());
			}
		}
		return mascaras;
	}
	
	private void carregarSoftware() {
		// TODO Auto-generated method stub
		Software software = this.softwareDao.carregarPorId(this.idSoftware);
		if (software != null) {
			this.nomeSoftware.setText(software.getNome());
			
			if (software.getValidade().getTime() != 0) {
				this.dataValidade = software.getValidade();
				this.calendar.setTime(this.dataValidade);
			} else {
				this.vencimentoIndefinido.setChecked(true);
			}
			this.btnVencimentoSoftware.setText(this.formatter.format(this.calendar.getTime()));
			
			Mascara mascara = this.mascaraDao.carregarPorId(String.valueOf(software.getMascaraId()));
			int indexSpinner = this.mascaras.indexOf(mascara.getFormato());
			this.spinnerMascara.setSelection(indexSpinner);
			
			this.numeroDeSerie.setText(software.getNumeroDeSerie());
		}
	}

	public void selecionarData(View view) {
		this.showDialog(view.getId());
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		if (id == R.id.vencimentoSoftware) {
			return new DatePickerDialog(this, new OnDateSetListener() {
				
				@Override
				public void onDateSet(DatePicker view, int year, int monthOfYear,
						int dayOfMonth) {
					// TODO Auto-generated method stub
					calendar.set(year, monthOfYear, dayOfMonth);
					dataValidade = calendar.getTime();
					btnVencimentoSoftware.setText(formatter.format(calendar.getTime()));
				}
			}, this.calendar.get(Calendar.YEAR), this.calendar.get(Calendar.MONTH), this.calendar.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}
	
	public void salvarSoftware(View view) {
		Integer id = null;
		if (this.idSoftware != null) {
			id = Integer.valueOf(this.idSoftware);
		}
		if (this.vencimentoIndefinido.isChecked()) {
			this.dataValidade = null;
		}
		String formato = this.mascaras.get(this.spinnerMascara.getSelectedItemPosition());
		Mascara mascara = this.mascaraDao.carregarPorFormato(formato);
		Software software = new Software(id, this.nomeSoftware.getText().toString(), this.dataValidade, this.numeroDeSerie.getText().toString(), mascara.getId());
		if (this.validaCampos() && this.softwareDao.salvarSoftware(software)) {
			Toast.makeText(this, R.string.registro_salvo, Toast.LENGTH_SHORT).show();
			this.finish();
		} else {
			Toast.makeText(this, R.string.erro_salvar, Toast.LENGTH_SHORT).show();
		}
	}
	
	private boolean validaCampos() {
		boolean resultado = false;
		int mascaraLength = this.mascaras.get(this.spinnerMascara.getSelectedItemPosition()).length();
		if (this.nomeSoftware.getText().toString().trim().length() > 0 &&
				this.numeroDeSerie.getText().toString().trim().length() == mascaraLength) {
			if (this.idSoftware == null || this.idSoftware.trim().length() == 0) {
				Software software = this.softwareDao.carregarPorNumeroDeSerie(this.numeroDeSerie.getText().toString());
				if (software == null) {
					resultado = true;
				}
			} else {
				resultado = true;
			}
		}
		return resultado;
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (!this.numeroDeSerie.isEnabled()) {
			this.numeroDeSerie.setEnabled(true);
		}
		if (this.numeroDeSerieMask != null) {
			this.numeroDeSerie.removeTextChangedListener(this.numeroDeSerieMask);
		}
		String formatoMascara = this.mascaras.get(this.spinnerMascara.getSelectedItemPosition());
		this.numeroDeSerieMask = Mask.insert(formatoMascara, this.numeroDeSerie);
		this.numeroDeSerie.addTextChangedListener(this.numeroDeSerieMask);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if (isChecked) {
			this.btnVencimentoSoftware.setEnabled(false);
		} else {
			this.btnVencimentoSoftware.setEnabled(true);
		}
	}

}
